﻿@{
    Layout = null;
}
@Html.AntiForgeryToken()
@using Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<link href="https://cdn.jsdelivr.net/npm/layui@2.8.18/dist/css/layui.css" rel="stylesheet" />
<script src="https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/layui@2.8.18/dist/layui.js"></script>
<style>
    .materiel-layout { display: flex; height: 90vh; }
    .materiel-tree { width: 260px; border-right: 1px solid #eee; padding: 10px; }
    .materiel-content { flex: 1; padding: 20px; }
    .tree-search { margin-bottom: 10px; }
    .layui-table-cell img { max-width: 40px; max-height: 40px; }
    .search-bar { display: flex; gap: 10px; align-items: center; margin-bottom: 10px; }
    .materiel-form { padding: 20px; }
    .materiel-form .layui-upload-img { width: 100px; height: 100px; margin: 10px 0; }
    .materiel-form .layui-form-item .layui-input-inline { width: 300px; }
    .required:before { content: '*'; color: red; margin-right: 4px; }
</style>
<div class="materiel-layout">
    <!-- 左侧树形 -->
    <div class="materiel-tree">
        <input type="text" id="treeSearch" class="layui-input tree-search" placeholder="请输入分类名称" />
        <ul id="materialTypeTree"></ul>
    </div>
    <!-- 右侧内容 -->
    <div class="materiel-content">
        <!-- 顶部搜索栏 -->
        <form class="layui-form search-bar" id="searchForm">
           
            <input type="text" name="MaterielCode" placeholder="物料编码" class="layui-input" style="width:150px;">
            <input type="text" name="MaterielName" placeholder="物料名称" class="layui-input" style="width:150px;">
            <button class="layui-btn" lay-submit lay-filter="search">搜索</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </form>
        <!-- 操作按钮 -->
        <div style="margin-bottom:10px;">
            <button class="layui-btn layui-btn-sm" id="btnAdd">+ 新增</button>
            <button class="layui-btn layui-btn-sm layui-btn-danger" id="btnBatchDelete">批量删除</button>
            <!-- <button class="layui-btn layui-btn-sm layui-btn-disabled" disabled id="btnEdit">修改</button> -->
        </div>
        <!-- 表格 -->
        <table class="layui-hide" id="materielTable" lay-filter="materielTable"></table>
    </div>
</div>

<!-- 新增/编辑弹窗 -->
<script type="text/html" id="materielFormTpl">
    <form class="layui-form materiel-form" lay-filter="materielForm" style="padding: 20px;">
        @Html.AntiForgeryToken()
        <input type="hidden" name="Id" value="0">
        <div class="layui-form-item">
            <div class="layui-inline" style="margin-right: 50px;">
                <label class="layui-form-label" style="width: 90px;"><span style="color: #ff4d4f;">*</span>物料编码</label>
                <div class="layui-input-inline" style="width: 300px; position: relative;">
                    <input type="text" name="MaterielCode" required lay-verify="required" placeholder="请输入物料编码" class="layui-input" id="materielCodeInput">
                    <input type="checkbox" name="AutoGenerate" lay-skin="switch" lay-filter="autoGenerateCode" title="自动生成" id="autoGenerateCode" style="position: absolute; right: -80px; top: 8px;">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 90px;"><span style="color: #ff4d4f;">*</span>物料名称</label>
                <div class="layui-input-inline" style="width: 300px;">
                    <input type="text" name="MaterielName" required lay-verify="required" placeholder="请输入物料名称" class="layui-input">
                </div>
            </div>
        </div>
        
        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 90px;">规格型号</label>
            <div class="layui-input-block" style="margin-left: 90px;">
                <textarea name="Specifications" placeholder="请输入规格型号" class="layui-textarea"></textarea>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline" style="margin-right: 50px;">
                <label class="layui-form-label" style="width: 90px;"><span style="color: #ff4d4f;">*</span>单位</label>
                <div class="layui-input-inline" style="width: 300px;">
                    <select name="UnitsId" lay-verify="required">
                        <option value="">请选择单位</option>
                        <option value="个">个</option>
                        <option value="件">件</option>
                        <option value="套">套</option>
                        <option value="箱">箱</option>
                        <option value="kg">kg</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 90px;"><span style="color: #ff4d4f;">*</span>物料/产品分类</label>
                <div class="layui-input-inline" style="width: 300px;">
                    <input type="hidden" name="MaterielTypeId" id="selectedTypeId" lay-verify="required" lay-reqtext="请选择物料分类">
                    <input type="text" id="materielType" readonly required lay-verify="required" placeholder="请选择所属分类" class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline" style="margin-right: 50px;">
                <label class="layui-form-label" style="width: 90px;">是否启用</label>
                <div class="layui-input-inline" style="width: 300px;">
                    <input type="radio" name="IsEnable" value="true" title="是" checked>
                    <input type="radio" name="IsEnable" value="false" title="否">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label" style="width: 90px;">安全库存</label>
                <div class="layui-input-inline" style="width: 300px;">
                    <input type="radio" name="IsSecure" value="1" title="是">
                    <input type="radio" name="IsSecure" value="0" title="否" checked>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 90px;">物料图片</label>
            <div class="layui-input-block" style="margin-left: 90px;">
                <!--
                <input type="hidden" name="MaterielUrl" id="materielUrl">
                <div class="layui-upload-drag" id="materielImgUpload" style="width: 150px; height: 150px; padding: 10px;">
                    <i class="layui-icon layui-icon-upload" style="font-size: 30px;"></i>
                    <p style="margin-top: 10px;">点击上传，或将图片拖拽到此处</p>
                    <div class="layui-hide" id="uploadPreview">
                        <img src="" alt="上传成功后渲染" style="max-width: 130px; max-height: 130px;">
                    </div>
                </div>
                <button type="button" class="layui-btn layui-btn-danger layui-btn-sm layui-hide" id="deleteImg" style="margin-top: 10px;">删除图片</button>
                <div style="margin-top: 5px; color: #999;">请上传大小不超过 5MB 格式为 png/jpg/jpeg 的文件</div>
                -->
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label" style="width: 90px;">备注</label>
            <div class="layui-input-block" style="margin-left: 90px;">
                <textarea name="Remark" placeholder="请输入内容" class="layui-textarea"></textarea>
            </div>
        </div>

        <div class="layui-form-item" style="margin-top: 30px; text-align: center;">
            <button class="layui-btn" lay-submit lay-filter="materielSubmit" style="margin-right: 10px;">确定</button>
            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll();">关闭</button>
        </div>
    </form>
</script>

<script type="text/html" id="imgTpl">
    {{#  if(d.materielUrl){ }}
      <img src="{{d.materielUrl}}" alt="图片" />
    {{#  } else { }}
      <i class="layui-icon layui-icon-picture" style="font-size:24px;color:#ccc;"></i>
    {{#  } }}
</script>
<script type="text/html" id="switchTpl">
    <input type="checkbox" name="isEnable" value="{{d.isEnable}}" lay-skin="switch" lay-text="是|否" {{ d.isEnable ? 'checked' : '' }} disabled>
</script>
<script type="text/html" id="safeStockTpl">
    <span class="layui-badge {{d.isSecure === 1 ? 'layui-bg-blue' : 'layui-bg-gray'}}">{{d.isSecure === 1 ? '是' : '否'}}</span>
</script>
<script type="text/html" id="isEnableTpl">
    <span class="layui-badge {{d.isEnable ? 'layui-bg-blue' : 'layui-bg-gray'}}">{{d.isEnable ? '是' : '否'}}</span>
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="rowDelete">删除</a>
</script>

<script>
$(function(){
    layui.use(['tree', 'table', 'form', 'layer', 'upload'], function(){
        var tree = layui.tree, table = layui.table, form = layui.form, layer = layui.layer, upload = layui.upload;
        var selectedTypeId = null;
        var editData = null;

        // 加载树形数据
        function loadTree(keyword) {
            $.get('/ProductionSystem/MasterData/GetMaterialTypeTree', function(res){
                if (!res.data) {
                    layer.msg('获取分类数据失败');
                    return;
                }
                var treeData = res.data;
                if (keyword) {
                    // 递归过滤
                    function filterTree(nodes) {
                        return nodes.filter(function(node){
                            var match = node.label.toLowerCase().indexOf(keyword.toLowerCase()) !== -1;
                            if (node.children && node.children.length) {
                                node.children = filterTree(node.children);
                                match = match || node.children.length > 0;
                            }
                            return match;
                        });
                    }
                    treeData = filterTree(treeData);
                }
                // 递归展开所有节点
                function expandAll(nodes) {
                    nodes.forEach(function(node){
                        node.spread = true;
                        if(node.children && node.children.length){
                            expandAll(node.children);
                        }
                    });
                }
                expandAll(treeData);
                tree.render({
                    elem: '#materialTypeTree',
                    data: treeData,
                    onlyIconControl: true,
                    click: function(obj){
                        selectedTypeId = obj.data.id;
                        reloadTable();
                    }
                });
            });
        }
        loadTree();

        // 树形搜索
        var searchTimer = null;
        $('#treeSearch').on('input', function(){
            clearTimeout(searchTimer);
            var value = $(this).val();
            searchTimer = setTimeout(function() {
                loadTree(value);
            }, 300);
        });

        // 表格渲染
        function reloadTable(params) {
            params = params || {};
            if (selectedTypeId) params.MaterielTypeId = selectedTypeId;
            table.reload('materielTable', {
                where: params,
                page: {curr: 1}
            });
        }
        table.render({
            elem: '#materielTable',
            url: '/ProductionSystem/MasterData/QueryMateriel',
            method: 'get',
            page: true,
            limit: 10,
            request: {
                pageName: 'PageIndex',
                limitName: 'PageSize'
            },
            parseData: function(res) {
                return {
                    "code": 0,
                    "msg": "",
                    "count": res.count,
                    "data": res.data
                };
            },
            where: {},
            cols: [[
                {type:'checkbox', fixed: 'left'},
                {field:'materielCode', title:'物料编码', width: 120},
                {field:'materielName', title:'物料名称', width: 150},
                {field:'materielUrl', title:'物料图片', templet:'#imgTpl', width: 100},
                {field:'specifications', title:'规格型号', width: 120},
                {field:'unitsId', title:'单位', width: 80},
               
                {field:'materialTypeName', title:'所属分类', width: 120},
                {field:'isEnable', title:'是否启用', templet:'#isEnableTpl', align:'center', width: 100},
                {field:'isSecure', title:'设置安全库存', templet:'#safeStockTpl', align:'center', width: 120},
                {field:'createTime', title:'创建时间', width: 160},
                {title:'操作', toolbar:'#barDemo', fixed: 'right', width: 120}
            ]],
            done: function() {
                var checkStatus = table.checkStatus('materielTable');
                updateButtonStatus(checkStatus);
            }
        });

        // 查询
        form.on('submit(search)', function(data){
            reloadTable(data.field);
            return false;
        });

        // 新增：监听重置按钮，清空分类和表单条件
        $('button[type=reset]').on('click', function() {
            selectedTypeId = null; // 清空分类
            $('#treeSearch').val(''); // 清空树搜索框
            reloadTable({}); // 重新加载表格，清空所有条件
        });

        // 更新按钮状态
        function updateButtonStatus(checkStatus) {
            if(checkStatus.data.length === 1) {
                $('#btnEdit').removeClass('layui-btn-disabled').removeAttr('disabled');
            } else {
                $('#btnEdit').addClass('layui-btn-disabled').attr('disabled', true);
            }
            
            if(checkStatus.data.length > 0) {
                $('#btnDelete').removeClass('layui-btn-disabled').removeAttr('disabled');
            } else {
                $('#btnDelete').addClass('layui-btn-disabled').attr('disabled', true);
            }
        }

        // 监听表格复选框选择
        table.on('checkbox(materielTable)', function(obj){
            var checkStatus = table.checkStatus('materielTable');
            updateButtonStatus(checkStatus);
        });

        // 雪花ID生成函数
        function generateSnowflakeId() {
            // 简单雪花算法实现（仅前端，实际可用后端生成）
            var timestamp = Date.now();
            var random = Math.floor(Math.random() * 1000);
            return timestamp.toString() + random.toString().padStart(3, '0');
        }
        // 用layui的form.on监听switch
        form.on('switch(autoGenerateCode)', function(data){
            if(data.elem.checked){
                var id = generateSnowflakeId();
                $('#materielCodeInput').val(id).prop('readonly', true);
            }else{
                $('#materielCodeInput').val('').prop('readonly', false);
            }
        });
        // 打开弹窗时初始化开关和物料编码
        function openDialog(title, data) {
            editData = data || null;
            layer.open({
                type: 1,
                title: title,
                area: ['650px', '700px'],
                content: $('#materielFormTpl').html(),
                success: function(layero, index) {
                    form.render();
                    // 自动生成物料编码开关初始化
                    var $codeInput = $('#materielCodeInput');
                    var $autoSwitch = $('#autoGenerateCode');
                    if(!editData){
                        $autoSwitch.prop('checked', false);
                        $codeInput.val('').prop('readonly', false);
                    }else{
                        $autoSwitch.prop('checked', false);
                        $codeInput.prop('readonly', false);
                    }
                    form.render('checkbox');
                    
                    // 初始化物料分类选择
                    $('#materielType').on('click', function(){
                        layer.open({
                            type: 1,
                            title: '选择物料分类',
                            area: ['300px', '500px'],
                            content: '<div id="typeSelectTree"></div>',
                            success: function(layero, index){
                                $.get('/ProductionSystem/MasterData/GetMaterialTypeTree', function(res){
                                    if (!res.data) {
                                        layer.msg('获取分类数据失败');
                                        return;
                                    }
                                    // 递归展开所有节点
                                    function expandAll(nodes) {
                                        nodes.forEach(function(node){
                                            node.spread = true;
                                            if(node.children && node.children.length){
                                                expandAll(node.children);
                                            }
                                        });
                                    }
                                    expandAll(res.data);
                                    tree.render({
                                        elem: '#typeSelectTree',
                                        data: res.data,
                                        onlyIconControl: true,
                                        click: function(obj){
                                            $('#selectedTypeId').val(obj.data.id);
                                            $('#materielType').val(obj.data.label);
                                            layer.close(index);
                                        }
                                    });
                                });
                            }
                        });
                    });

                    // 如果是编辑模式，填充表单数据
                    if(editData) {
                        setTimeout(function(){
                            // 直接赋值隐藏域和显示框
                            $('#selectedTypeId').val(editData.materielTypeId || '');
                            $('#materielType').val(editData.category || '');
                            // 用 form.val 赋值
                            form.val('materielForm', {
                                "Id": editData.id,
                                "MaterielCode": editData.materielCode,
                                "MaterielName": editData.materielName,
                                "MaterielUrl": editData.materielUrl,
                                "Specifications": editData.specifications,
                                "UnitsId": editData.unitsId,
                                "MaterielTypeId": editData.materielTypeId || '',
                                "IsEnable": editData.isEnable ? "true" : "false",
                                "IsSecure": editData.isSecure === 1 ? "1" : "0",
                                "Remark": editData.remark
                            });
                            form.render();
                            if(editData.materielUrl){
                                $('#uploadPreview').html('<img src="'+editData.materielUrl+'" style="max-width:130px;max-height:130px;">');
                            }
                        }, 200);
                    }
                }
            });
        }

        // 新增按钮点击事件
        $('#btnAdd').on('click', function(){
            openDialog('新增物料');
        });

        // 编辑按钮点击事件
        $('#btnEdit').on('click', function(){
            var checkStatus = table.checkStatus('materielTable');
            if(checkStatus.data.length === 1) {
                openDialog('编辑物料', checkStatus.data[0]);
            }
        });

        // 删除按钮点击事件
        $('#btnDelete').on('click', function(){
            var checkStatus = table.checkStatus('materielTable');
            if(checkStatus.data.length > 0) {
                layer.confirm('确定删除选中的记录？', function(index){
                    var ids = checkStatus.data.map(function(item){ return item.id; });
                    var token = $('input[name="__RequestVerificationToken"]').val();
                    $.ajax({ 
                        url: '/ProductionSystem/MasterData/BatchDeleteMateriel',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(ids),
                        headers: {
                            'RequestVerificationToken': token
                        },
                        success: function(res){
                            if(res.code === 0) {
                                layer.msg('删除成功');
                                reloadTable();
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                        },
                        error: function() {
                            layer.msg('操作失败，请重试');
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 监听工具条
        table.on('tool(materielTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                openDialog('编辑物料', data);
            } else if(obj.event === 'rowDelete'){
                layer.confirm('确定删除此记录？', function(index){
                    var id = data.id || data.Id;
                    if(!id){
                        layer.msg('未获取到ID，无法删除');
                        return;
                    }
                    var token = $('input[name="__RequestVerificationToken"]').val();
                    $.ajax({
                        url: '/ProductionSystem/MasterData/BatchDeleteMateriel',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify([id]),
                        headers: {
                            'RequestVerificationToken': token
                        },
                        success: function(res){
                            if(res.code === 0) {
                                layer.msg('删除成功');
                                reloadTable();
                            } else {
                                layer.msg('删除失败: ' + (res.msg || JSON.stringify(res)));
                            }
                        },
                        error: function(xhr) {
                            layer.msg('操作失败: ' + (xhr.responseText || ''));
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 监听表单提交
        form.on('submit(materielSubmit)', function(data){
            var formData = data.field;
            // 删除 token 字段，避免传到后端
            delete formData.__RequestVerificationToken;
            // 处理布尔值和数字
            formData.IsEnable = formData.IsEnable === 'true';
            formData.IsSecure = formData.IsSecure === '1' ? 1 : 0;
            formData.Id = parseInt(formData.Id) || 0;
            formData.MaterielTypeId = parseInt(formData.MaterielTypeId);
            // 验证必填字段
            if (!formData.MaterielCode) {
                layer.msg('请输入物料编码');
                return false;
            }
            if (!formData.MaterielName) {
                layer.msg('请输入物料名称');
                return false;
            }
            if (!formData.UnitsId) {
                layer.msg('请输入单位');
                return false;
            }
            if (!formData.MaterielTypeId) {
                layer.msg('请选择物料分类');
                return false;
            }
            var url = formData.Id === 0 ? '/ProductionSystem/MasterData/CreateMateriel' : '/ProductionSystem/MasterData/UpdateMateriel';
            var method = 'POST';
            var token = $('input[name="__RequestVerificationToken"]').val();
            formData.MaterielUrl = "https://dummyimage.com/100x100/cccccc/000000&text=Demo";
            $.ajax({
                url: url,
                type: method,
                contentType: 'application/json',
                data: JSON.stringify(formData),
                headers: {
                    'RequestVerificationToken': token
                },
                success: function(res){
                    if(res.success) {
                        layer.closeAll('page');
                        layer.msg(res.message);
                        reloadTable();
                    } else {
                        layer.msg(res.message || '操作失败');
                    }
                },
                error: function() {
                    layer.msg('操作失败，请重试');
                }
            });
            return false;
        });

        // 批量删除按钮点击事件
        $('#btnBatchDelete').on('click', function(){
            var checkStatus = table.checkStatus('materielTable');
            if(checkStatus.data.length > 0) {
                layer.confirm('确定批量删除选中的记录？', function(index){
                    var ids = checkStatus.data.map(function(item){ return item.id; });
                    var token = $('input[name="__RequestVerificationToken"]').val();
                    $.ajax({
                        url: '/ProductionSystem/MasterData/BatchDeleteMateriel',
                        type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(ids),
                        headers: {
                            'RequestVerificationToken': token
                        },
                        success: function(res){
                            if(res.code === 0) {
                                layer.msg('批量删除成功');
                                reloadTable();
                            } else {
                                layer.msg(res.msg || '批量删除失败');
                            }
                        },
                        error: function() {
                            layer.msg('操作失败，请重试');
                        }
                    });
                    layer.close(index);
                });
            } else {
                layer.msg('请先选择要删除的记录');
            }
        });
    });
});
</script>